package com.cszy.yydqbfq.ext

import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * 获取输入框的值
 */
fun EditText.text(): String {
    return text.toString().trim()
}

/**
 * 延迟监听输入框值
 */
fun EditText.addDelayedTextChangeListener(delayMillis: Long = 500, onTextChanged: (String) -> Unit) {
    val handler = Handler()
    var runnable: Runnable? = null
    val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            runnable?.let { handler.removeCallbacks(it) }
        }

        override fun afterTextChanged(s: Editable?) {
            runnable = Runnable { onTextChanged(s.toString()) }
            handler.postDelayed(runnable!!, delayMillis)
        }
    }
    addTextChangedListener(textWatcher)
}